//
//  CSHTTPDownloadWork.m
//  花式下载文件
//
//  Created by 姚彦兆 on 15/10/20.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

#import "CSHTTPDownloadWork.h"
#import <UIKit/UIKit.h>
@interface CSHTTPDownloadWork()

@end

@implementation CSHTTPDownloadWork

-(void)saveFileWithFilePath:(NSString *)filePath
            andDownloadData:(NSData *)downloadData
        andDownloadResponse:(NSURLResponse *)downloadResponse{
    
    //NSString * filePath = [NSString stringWithFormat:@"/Users/Masteryyz/Desktop/download"];
    
    NSLog(@"已经下载完毕");
    
    NSString * type = downloadResponse.MIMEType ;
    
    NSLog(@"%@" , type);
    
    type = [type stringByReplacingOccurrencesOfString:@"application/" withString:@""];
    
    NSLog(@"%@" , type);
    
    [downloadData writeToFile:[filePath stringByAppendingString:[NSString stringWithFormat:@".%@", type]] atomically:YES];

}

/**
 *  下载完成后在文件夹下存储文件的方法
 *
 *  @param directoriePath 需要存储的文件夹路径,可以指定不存在的文件夹,按情况新建
 *  @param fileName       存储在本地的文件名
 *  @param downloadData   下载完成的数据
 */
-(void)saveFileWithDirectoriePath:(NSString *)directoriePath
                      andFileName:(NSString *)fileName
                  andDownloadData:(NSData *)downloadData
              andDownloadResponse:(NSURLResponse *)downloadResponse{
    
    //NSString * filePath = [NSString stringWithFormat:@"/Users/Masteryyz/Desktop/download"];
    
    NSLog(@"已经下载完毕");
    
    NSString * type = downloadResponse.MIMEType ;
    
    type = [type stringByReplacingOccurrencesOfString:@"application/" withString:@""];

    NSFileManager * manager = [NSFileManager defaultManager];
    
    BOOL createDir = [manager createDirectoryAtPath:directoriePath withIntermediateDirectories:YES attributes:nil error:nil];
    
    if (createDir) {
        
        [downloadData writeToFile:[directoriePath stringByAppendingString:[NSString stringWithFormat:@"/%@.%@",fileName , type]] atomically:YES];
        
    }else{
        
        UIAlertController * controller = [[UIAlertController alloc]init];
        
        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        
        [controller addAction:act];
            
    }
    
}

@end
